package com.qianguo.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.eva.androidlibrary.api.entity.Config;
import com.eva.androidlibrary.api.entity.ResultData;
import com.eva.androidlibrary.utils.SharedPreferencesHelper;
import com.eva.androidlibrary.widget.mdedittext.MaterialEditText;
import com.eva.androidlibrary.widget.wheelpicker.core.AbstractWheelPicker;
import com.eva.androidlibrary.widget.wheelpicker.view.WheelCurvedPicker;
import com.qianguo.shop.R;
import com.eva.androidlibrary.api.HttpRequestCallback;
import com.qianguo.shop.base.BaseChooseImageActivity;
import com.qianguo.shop.constant.ShopKeys;
import com.qianguo.shop.constant.SpKeys;
import com.qianguo.shop.entity.Category;
import com.qianguo.shop.entity.CategoryListBean;
import com.eva.androidlibrary.api.entity.Product;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * 编辑商品页面
 *
 * @author GUXIA318
 * @date 2015-11-27 9:58
 */
@EActivity(R.layout.activity_product_add_or_edit)
public class AddOrEditProductActivity extends BaseChooseImageActivity {

    /** 名称 */
    @ViewById(R.id.product_add_name_edit_text)
    MaterialEditText mEdtName;

    /** 产地 */
    @ViewById(R.id.product_add_product_field_edit_text)
    MaterialEditText mEdtField;

    /** 品类 */
    @ViewById(R.id.product_add_category_text_view)
    TextView mTvCategory;

    /** 售价 */
    @ViewById(R.id.product_add_price_edit_text)
    MaterialEditText mEdtPrice;

    /** 封面 */
    @ViewById(R.id.product_add_cover_image_view)
    ImageView mImgCover;

    /** 大图 */
    @ViewById(R.id.product_add_pic_image_view)
    ImageView mImgPic;

    /** 商品简介 */
    @ViewById(R.id.product_add_intro_edit_text)
    EditText mEdtIntro;

    /** 产品规格 */
    @ViewById(R.id.product_add_produce_unit_text_view)
    TextView mTvProductUnit;

    @Extra(ShopKeys.EXTRA_KEY_PRODUCT)
    Product mProduct;

    @Extra(ShopKeys.EXTRA_KEY_SHOP_ID)
    String mShopID;

    private WheelCurvedPicker mCategoryPicker;
    private PopupWindow mCategoryPopupWindow;
    private List<Category> mCategories;
    private List<String> mCategoryNames = new ArrayList<>();
    private String mCategoryName;

    private WheelCurvedPicker mUnitPicker;
    private PopupWindow mUnitPopupWindow;
    private List<String> mUnits = new ArrayList<>();
    private Product mCopyProduct;

    public static void jumpToEditProduct(Context context, String shopId, Product product) {
        Intent intent = new Intent();
        intent.setClass(context, com.qianguo.shop.activity.AddOrEditProductActivity_.class);
        intent.putExtra(ShopKeys.EXTRA_KEY_PRODUCT, product);
        intent.putExtra(ShopKeys.EXTRA_KEY_SHOP_ID, shopId);
        context.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return getString(R.string.product_add_title);
    }

    @Override
    protected void initializeUI() {
        if (mProduct != null) {
            mEdtName.setText(mProduct.getName());
            mTvCategory.setText(mProduct.getCategoryName());
            mEdtField.setText(mProduct.getRegion());
            mEdtPrice.setText(String.valueOf(mProduct.getPrice()));
            mTvProductUnit.setText(mProduct.getUnit());
            mImageLoader.loadImage(this, mImgCover, mProduct.getCover());
            mEdtIntro.setText(mProduct.getIntro());
            try {
                mCopyProduct = (Product) mProduct.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        } else {
            mCopyProduct = new Product();
            mCopyProduct.setShopId(mShopID);
        }

        mUnits = SharedPreferencesHelper.getInstance(this).getArrayList(SpKeys.CACHE_KEY_UNIT);
    }

    /**
     * 选择品类
     */
    @Click(R.id.product_add_category_layout)
    void clickCategory() {
        if (mCategories == null) {
            getCategories();
        } else {
            showCategoryChooser();
        }
    }

    /**
     * 选择规格
     */
    @Click(R.id.product_add_product_unit_layout)
    void clickUnit() {
        if (mUnits == null || mUnits.size() == 0) {
            getUnits();
        } else {
            showUnitChooser();
        }
    }

    @Click(R.id.product_add_cover_image_view)
    void clickCover() {
        showPickerDialog(new PicPickerCallback() {
            @Override
            public void afterPick(String filePath) {
                // TODO: 16/6/12 上传图片
                mImageLoader.loadImage(AddOrEditProductActivity.this, mImgCover, filePath);
            }
        });

    }

    @Click(R.id.product_add_ok_button)
    void clickOk() {
        mCopyProduct.setName(mEdtName.getText().toString());
        mCopyProduct.setPrice(Float.valueOf(mEdtPrice.getText().toString()));
        mCopyProduct.setRegion(mEdtField.getText().toString());
        mCopyProduct.setIntro(mEdtIntro.getText().toString());
        if (validateInfo(mCopyProduct)) {
            if (mProduct == null) {
                add(mCopyProduct);
            } else {
                edit(mProduct, mCopyProduct);
            }
        }
    }

    /**
     * 修改产品
     *
     * @param origin
     * @param copy
     */
    @Background
    void edit(Product origin, Product copy) {
        mApp.getApi().editProduct(mApp.getUser().getToken(), origin, copy, new HttpRequestCallback<ResultData>() {
            @Override
            public void onSuccess(int code, String msg, ResultData data) {
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditProductActivity.this, msg);
            }
        });
    }

    /**
     * 添加产品
     *
     * @param product
     */
    @Background
    void add(Product product) {
        mApp.getApi().addProduct(mApp.getUser().getToken(), product, new HttpRequestCallback<Product>() {
            @Override
            public void onSuccess(int code, String msg, Product data) {
                // TODO: 16/6/12
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditProductActivity.this, msg);
            }
        });

    }

    /**
     * 检测提交信息的正确性
     *
     * @return
     */
    private boolean validateInfo(Product product) {
        // TODO: 15/11/29 检测信息
        if (TextUtils.isEmpty(product.getName())) {
            mEdtName.setError(getString(R.string.product_add_hint_name));
            return false;
        }

        if (product.getCategoryId() <= 0) {
            showSnackBar(this, getString(R.string.product_add_hint_category));
            return false;
        }

        if (TextUtils.isEmpty(product.getUnit())) {
            showSnackBar(this, getString(R.string.product_add_hint_unit));
            return false;
        }

        if (product.getPrice() <= 0) {
            mEdtPrice.setError(getString(R.string.product_add_hint_price));
            return false;
        }
        return true;
    }

    /**
     * 获取商品规格
     */
    @Background
    void getUnits() {
        mApp.getApi().getCommonConfig(new HttpRequestCallback<Config>() {
            @Override
            public void onSuccess(int code, String msg, Config data) {
                // TODO: 16/6/12 缓存
                SharedPreferencesHelper.getInstance(mContext).putArrayList(SpKeys.CACHE_KEY_UNIT, data.getUnit());
                mUnits.addAll(data.getUnit());
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditProductActivity.this, msg);
            }
        });

    }

    /**
     * 获取商品品类列表
     */
    @Background
    void getCategories() {
        mApp.getApi().getCategories("", new HttpRequestCallback<CategoryListBean>() {
            @Override
            public void onSuccess(int code, String msg, CategoryListBean data) {
                mCategories = data.getList();
                for (Category category : mCategories) {
                    mCategoryNames.add(category.getName());
                }
                showCategoryChooser();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(AddOrEditProductActivity.this, msg);
            }
        });

    }


    @UiThread
    void showCategoryChooser() {
        if (mCategoryPicker == null) {
            mCategoryPicker = new WheelCurvedPicker(this);
            mCategoryPicker.setData(mCategoryNames);
            mCategoryPicker.setBackgroundColor(getResources().getColor(R.color.secondary_text_color));
            mCategoryPicker.setCurrentTextColor(getResources().getColor(android.R.color.white));
            mCategoryPicker.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
                @Override
                public void onWheelScrolling(float deltaX, float deltaY) {

                }

                @Override
                public void onWheelSelected(int index, String data) {
                    mCopyProduct.setCategoryId(mCategories.get(index).getCategoryId());
                    mCategoryName = data;
                }

                @Override
                public void onWheelScrollStateChanged(int state) {

                }
            });
        }

        if (mCategoryPopupWindow == null) {
            mCategoryPopupWindow = new PopupWindow();
            mCategoryPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mCategoryPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mCategoryPopupWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
            mCategoryPopupWindow.setContentView(mCategoryPicker);
            mCategoryPopupWindow.setFocusable(true);
            mCategoryPopupWindow.setOutsideTouchable(true);
            mCategoryPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mTvCategory.setText(mCategoryName);
                }
            });
        }

        mCategoryPopupWindow.showAtLocation(mToolbar, Gravity.BOTTOM, 0, 0);
    }

    @UiThread
    void showUnitChooser() {
        if (mUnitPicker == null) {
            mUnitPicker = new WheelCurvedPicker(this);
            mUnitPicker.setData(mUnits);
            mUnitPicker.setBackgroundColor(getResources().getColor(R.color.secondary_text_color));
            mUnitPicker.setCurrentTextColor(getResources().getColor(android.R.color.white));
            mUnitPicker.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
                @Override
                public void onWheelScrolling(float deltaX, float deltaY) {

                }

                @Override
                public void onWheelSelected(int index, String data) {
                    mCopyProduct.setUnit(data);
                }

                @Override
                public void onWheelScrollStateChanged(int state) {

                }
            });
        }

        if (mUnitPopupWindow == null) {
            mUnitPopupWindow = new PopupWindow();
            mUnitPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mUnitPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mUnitPopupWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
            mUnitPopupWindow.setContentView(mUnitPicker);
            mUnitPopupWindow.setFocusable(true);
            mUnitPopupWindow.setOutsideTouchable(true);
            mUnitPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mTvProductUnit.setText(mCopyProduct.getUnit());
                }
            });
        }

        mUnitPopupWindow.showAtLocation(mToolbar, Gravity.BOTTOM, 0, 0);
    }

}
